package com.planet_ink.ZipCodeWeather.services;

import java.util.LinkedList;

import com.sun.jersey.api.client.Client;

/**
 * This class maintains a collection of jersey web clients for reuse  
 * @author Bo Zimmerman
 */
public class HttpClientFactory
{
	private static final int 			   DEFAULT_MAXIMUM_CLIENTS	= 20;
	private static final HttpClientFactory defaultInstance 			= new HttpClientFactory();
	
	private final int maximumNumberOfClients;
	private LinkedList<Client> clients = new LinkedList<Client>();
	
	
	public HttpClientFactory(int numberOfClients)
	{
		this.maximumNumberOfClients = numberOfClients;
	}
	
	public HttpClientFactory()
	{
		this.maximumNumberOfClients = DEFAULT_MAXIMUM_CLIENTS;
	}
	
	public static HttpClientFactory defaultInstance()
	{
		return defaultInstance;
	}
	
	public Client getHttpClient()
	{
		if(clients.size() > 0)
		{
			synchronized(clients)
			{
				if(clients.size() > 0)
				{
					return clients.removeFirst();
				}
			}
		}
		return Client.create();
	}
	
	public void giveBackClient(final Client client)
	{
		if(clients.size() < maximumNumberOfClients)
		{
			synchronized(clients)
			{
				if(clients.size() < maximumNumberOfClients)
				{
					clients.addLast(client);
					return;
				}
			}
		}
		client.destroy();
	}
}
